const app = getApp()
const api = require('../../utils/api/index');

Page({
  data: {
    selectedDate: '',
    formattedDate: '',
    weekRange: '',
    // 每周目标数据
    aerobicMinutes: 0,
    aerobicGoal: 150,
    aerobicProgress: 0,
    resistanceCount: 0,
    resistanceGoal: 2,
    resistanceProgress: 0,
    flexibilityCount: 0,
    flexibilityGoal: 2,
    flexibilityProgress: 0,
    // 血糖安全提示
    currentTip: 0,
    safetyTips: [
      {
        id: 1,
        icon: '⚠️',
        title: '运动前血糖安全范围',
        description: '运动前血糖应在5.6-13.9mmol/L之间。低于5.6mmol/L时，请先摄入15-20g碳水化合物；高于13.9mmol/L时，检测酮体并避免剧烈运动。'
      },
      {
        id: 2,
        icon: '⏱️',
        title: '最佳运动时间',
        description: '餐后1-2小时是运动的理想时间，可有效降低餐后血糖峰值。若使用胰岛素或降糖药，请遵医嘱调整用药时间。'
      },
      {
        id: 3,
        icon: '🔍',
        title: '运动禁忌提醒',
        description: '如您有心脑血管疾病、严重视网膜病变或肾功能不全，请在医师评估下进行运动。使用胰岛素者运动前后需监测血糖。'
      },
      {
        id: 4,
        icon: '💧',
        title: '水分与安全',
        description: '运动前、中、后保持充分水分摄入。首次尝试新运动时应有人陪伴，准备含糖食物以防低血糖。'
      }
    ],
    // 运动记录
    totalCaloriesBurned: 0,
    exercises: [],
    // 运动建议
    recommendation: {
      title: '增加日常活动量',
      content: '除了规律的锻炼外，建议增加日常活动，如步行上班、使用楼梯代替电梯、每小时站立活动5分钟等。这些小的活动增加对控制血糖也有显著帮助。'
    },
    showDatePickerModal: false,
    // 添加一个loading状态
    loading: false,
    // 周统计数据
    weeklyStats: null,
    // 添加计时器变量
    tipAutoplayTimer: null
  },

  onLoad() {
    this.initDateData();
    
    // 初始化健身建议
    this.refreshRecommendation();
  },

  onShow() {
    // 更新底部TabBar选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      });
    }
    
    // 加载当天的运动数据
    this.loadExerciseData(this.data.selectedDate);
    
    // 加载周统计数据
    this.loadWeeklyStats();
  },
  
  onHide() {
    // 页面隐藏时清除轮播计时器
    this.clearTipAutoplay();
  },
  
  onUnload() {
    // 页面卸载时清除轮播计时器
    this.clearTipAutoplay();
  },
  
  // 启动安全提示自动轮播
  startTipAutoplay() {
    // 每5秒自动切换到下一个提示
    const timer = setInterval(() => {
      const nextTip = (this.data.currentTip + 1) % this.data.safetyTips.length;
      this.setData({
        currentTip: nextTip
      });
    }, 5000); // 5秒切换一次
    
    this.setData({
      tipAutoplayTimer: timer
    });
  },
  
  // 清除安全提示自动轮播
  clearTipAutoplay() {
    if (this.data.tipAutoplayTimer) {
      clearInterval(this.data.tipAutoplayTimer);
      this.setData({
        tipAutoplayTimer: null
      });
    }
  },
  
  // 提示轮播变化
  onTipChange(e) {
    this.setData({
      currentTip: e.detail.current
    });
  },

  // 手动切换提示
  changeTip(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentTip: index
    });
  },

  // 初始化日期数据
  initDateData() {
    const today = new Date();
    const selectedDate = this.formatDateForPicker(today);
    const formattedDate = this.formatDateForDisplay(today);
    const weekRange = this.getWeekRange(today);

    this.setData({
      selectedDate,
      formattedDate,
      weekRange
    });
  },

  // 格式化日期为选择器格式 (YYYY-MM-DD)
  formatDateForPicker(date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  // 格式化日期为显示格式 (YYYY-MM-DD)
  formatDateForDisplay(date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  // 获取当前日期所在周的范围 (MM.DD-MM.DD)
  getWeekRange(date) {
    const currentDay = date.getDay();
    const firstDay = new Date(date);
    firstDay.setDate(date.getDate() - currentDay);
    
    const lastDay = new Date(firstDay);
    lastDay.setDate(firstDay.getDate() + 6);
    
    const firstMonth = firstDay.getMonth() + 1;
    const firstDate = firstDay.getDate();
    const lastMonth = lastDay.getMonth() + 1;
    const lastDate = lastDay.getDate();
    
    return `${firstMonth}.${firstDate}-${lastMonth}.${lastDate}`;
  },

  // 加载每周运动统计
  async loadWeeklyStats() {
    this.setData({ loading: true });
    try {
      const response = await api.exercise.getWeeklyStats();
      if (response.success && response.data) {
        const stats = response.data;
        
        // 添加默认值处理
        stats.aerobicMinutes = stats.aerobicMinutes || 0;
        stats.aerobicGoal = stats.aerobicGoal || 150; // 根据指南设置默认目标
        stats.resistanceCount = stats.resistanceCount || 0;
        stats.resistanceGoal = stats.resistanceGoal || 2; // 根据指南每周2次
        
        // 添加柔韧与平衡训练数据
        stats.flexibilityCount = this.countExercisesByCategory(stats.dailyStats, '柔韧与平衡') || 0;
        stats.flexibilityGoal = 2; // 根据指南每周至少2次
        
        // 计算进度
        this.calculateProgress(stats);
        this.setData({ weeklyStats: stats });
      }
    } catch (error) {
      console.error('获取每周运动统计失败:', error);
      // 使用默认值
      this.calculateProgress({
        aerobicMinutes: 0,
        aerobicGoal: 150,
        resistanceCount: 0,
        resistanceGoal: 2,
        flexibilityCount: 0,
        flexibilityGoal: 2
      });
    } finally {
      this.setData({ loading: false });
    }
  },
  
  // 根据类别统计运动次数
  countExercisesByCategory(dailyStats, category) {
    if (!dailyStats || !Array.isArray(dailyStats)) return 0;
    
    let count = 0;
    dailyStats.forEach(day => {
      if (day.exercises) {
        day.exercises.forEach(exercise => {
          if (exercise.category === category) {
            count++;
          }
        });
      }
    });
    
    return count;
  },
  
  // 计算每周运动进度
  calculateProgress(stats) {
    // 计算有氧运动进度
    const aerobicProgress = Math.min(Math.round((stats.aerobicMinutes / stats.aerobicGoal) * 100), 100);
    
    // 计算抗阻训练进度
    const resistanceProgress = Math.min(Math.round((stats.resistanceCount / stats.resistanceGoal) * 100), 100);
    
    // 计算柔韧与平衡训练进度
    const flexibilityProgress = Math.min(Math.round((stats.flexibilityCount / stats.flexibilityGoal) * 100), 100);
    
    this.setData({
      aerobicMinutes: stats.aerobicMinutes || 0,
      aerobicGoal: stats.aerobicGoal || 150,
      aerobicProgress: aerobicProgress || 0,
      resistanceCount: stats.resistanceCount || 0,
      resistanceGoal: stats.resistanceGoal || 2,
      resistanceProgress: resistanceProgress || 0,
      flexibilityCount: stats.flexibilityCount || 0,
      flexibilityGoal: stats.flexibilityGoal || 2,
      flexibilityProgress: flexibilityProgress || 0
    });
  },

  // 日期改变
  onDateChange(e) {
    const selectedDate = e.detail.value;
    const date = new Date(selectedDate);
    const formattedDate = this.formatDateForDisplay(date);
    const weekRange = this.getWeekRange(date);
    
    this.setData({
      selectedDate,
      formattedDate,
      weekRange
    });
    
    // 加载选中日期的运动数据
    this.loadExerciseData(selectedDate);
  },

  // 前一天
  onPreviousDay() {
    const currentDate = new Date(this.data.selectedDate);
    currentDate.setDate(currentDate.getDate() - 1);
    
    const selectedDate = this.formatDateForPicker(currentDate);
    const formattedDate = this.formatDateForDisplay(currentDate);
    const weekRange = this.getWeekRange(currentDate);
    
    this.setData({
      selectedDate,
      formattedDate,
      weekRange
    });
    
    // 加载选中日期的运动数据
    this.loadExerciseData(selectedDate);
  },

  // 后一天
  onNextDay() {
    const currentDate = new Date(this.data.selectedDate);
    currentDate.setDate(currentDate.getDate() + 1);
    
    const selectedDate = this.formatDateForPicker(currentDate);
    const formattedDate = this.formatDateForDisplay(currentDate);
    const weekRange = this.getWeekRange(currentDate);
    
    this.setData({
      selectedDate,
      formattedDate,
      weekRange
    });
    
    // 加载选中日期的运动数据
    this.loadExerciseData(selectedDate);
  },

  // 加载运动数据
  async loadExerciseData(date) {
    if (!date) {
      date = this.data.selectedDate;
    }
    
    this.setData({ loading: true });
    
    try {
      // 使用API获取指定日期的运动数据
      const response = await api.exercise.getExercises({
        startDate: date,
        endDate: date
      });
      
      if (response.success) {
        // 处理API返回的数据
        const formattedExercises = response.data.map(exercise => ({
          id: exercise._id,
          name: exercise.type,
          icon: this.getExerciseIcon(exercise.type),
          duration: exercise.duration,
          timeFormatted: exercise.startTime,
          caloriesBurned: exercise.caloriesBurned,
          glucoseBefore: exercise.glucoseBefore,
          glucoseAfter: exercise.glucoseAfter,
          intensity: exercise.intensity,
          notes: exercise.notes
        }));
        
        this.setData({
          exercises: formattedExercises,
          totalCaloriesBurned: response.totalCalories || 0
        });
      } else {
        // 处理API返回的错误
        console.error('获取运动数据失败:', response.message);
        this.setData({
          exercises: [],
          totalCaloriesBurned: 0
        });
      }
    } catch (error) {
      console.error('获取运动数据异常:', error);
      this.setData({
        exercises: [],
        totalCaloriesBurned: 0
      });
      
      wx.showToast({
        title: '获取数据失败',
        icon: 'none',
        duration: 2000
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 获取运动图标
  getExerciseIcon(type) {
    const iconMap = {
      '步行': '🚶',
      '跑步': '🏃',
      '骑行': '🚴',
      '游泳': '🏊',
      '健身': '💪',
      '瑜伽': '🧘',
      '太极': '🧍',
      '跳舞': '💃',
      '球类运动': '⚽',
      '其他': '🏋️'
    };
    
    return iconMap[type] || '🏋️';
  },

  // 刷新运动建议
  refreshRecommendation() {
    const recommendations = [
      {
        title: '增加日常活动量',
        content: '除了规律的锻炼外，建议增加日常活动，如步行上班、使用楼梯代替电梯、每小时站立活动5分钟等。这些小的活动增加对控制血糖也有显著帮助。'
      },
      {
        title: '有氧与力量结合',
        content: '建议将有氧运动与力量训练结合起来，每周至少进行150分钟中等强度有氧运动和2-3次力量训练。这种组合可以最大化提高胰岛素敏感性。'
      },
      {
        title: '逐步增加运动量',
        content: '如果您之前很少运动，建议从低强度开始，如每天步行10-15分钟，然后逐渐增加时间和强度。运动计划应循序渐进，避免过度训练。'
      },
      {
        title: '间歇性高强度训练',
        content: '研究表明，短时间的高强度间歇训练(HIIT)对改善胰岛素敏感性非常有效。可以尝试1分钟高强度活动后休息1分钟，重复5-10次。'
      },
      {
        title: '餐后时间管理',
        content: '餐后1-2小时是进行有氧运动的理想时间，此时可以有效降低餐后血糖峰值。即使只有10-15分钟的短暂活动，也能产生显著效果。'
      }
    ];
    
    const index = Math.floor(Math.random() * recommendations.length);
    
    this.setData({
      recommendation: recommendations[index]
    });
    
    wx.showToast({
      title: '已更新建议',
      icon: 'success',
      duration: 1500
    });
  },

  // 跳转到运动详情
  navigateToExerciseDetail(e) {
    const exerciseId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `../exerciseDetail/exerciseDetail?id=${exerciseId}`,
      fail: (error) => {
        console.error('导航到运动详情失败:', error);
        wx.showToast({
          title: '页面开发中',
          icon: 'none',
          duration: 2000
        });
      }
    });
  },

  // 跳转到添加运动
  navigateToAddExercise() {
    wx.navigateTo({
      url: '../exerciseAdd/exerciseAdd',
      fail: () => {
        wx.showToast({
          title: '功能开发中',
          icon: 'none',
          duration: 2000
        });
      }
    });
  },

  showDatePicker() {
    this.setData({
      showDatePickerModal: true
    });
  },

  hideDatePicker() {
    this.setData({
      showDatePickerModal: false
    });
  },

  dateChange(e) {
    const newDate = e.detail.value;
    this.setData({
      selectedDate: newDate,
      formattedDate: newDate // 日期选择器返回的已经是格式化的日期字符串，无需再次格式化
    });
    this.loadExerciseData(newDate);
    this.hideDatePicker();
  },

  formatDate(date) {
    if (!date) date = new Date();
    
    // 如果传入的是字符串，先转换为Date对象
    if (typeof date === 'string') {
      // 尝试解析日期字符串
      const parts = date.split('-');
      if (parts.length === 3) {
        // 创建新的Date对象 (月份要减1，因为Date对象中月份是0-11)
        date = new Date(
          parseInt(parts[0], 10),
          parseInt(parts[1], 10) - 1,
          parseInt(parts[2], 10)
        );
      } else {
        // 如果无法解析，使用当前日期
        date = new Date();
      }
    }
    
    // 确保date是一个有效的Date对象
    if (!(date instanceof Date) || isNaN(date.getTime())) {
      date = new Date();
    }
    
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  },
}) 